/**
 * 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
 * <p>
 * 说明:
 * 1 ≤ m ≤ n ≤ 链表长度。
 * <p>
 * 示例:
 * <p>
 * 输入: 1->2->3->4->5->NULL, m = 2, n = 4
 * 输出: 1->4->3->2->5->NULL
 */
class Solution {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;
        ListNode node3 = new ListNode(3);
        node2.next = node3;
        ListNode node4 = new ListNode(4);
        node3.next = node4;
        ListNode node5 = new ListNode(5);
        node4.next = node5;
        ListNode node = reverseBetween(node1, 2, 4);
        System.out.println(node);
    }

    public static ListNode reverseBetween(ListNode head, int m, int n) {
        int[] store = new int[n - m + 1];
        ListNode node = head;
        ListNode start = null;
        for (int i = 1; i <= n; i++, node = node.next) {
            if (i > m) {
                store[i - m] = node.val;
            } else if (i == m) {
                start = node;
                store[0] = node.val;
            }
        }
        for (int i = n - m; i >= 0; i--, start = start.next) {
            start.val = store[i];
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}